using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.demo.IRepositories;
using System.Collections.Generic;
using VOL.Entity.DomainModels;
using VOL.demo.IServices;
using VOL.Core.Extensions.AutofacManager;

namespace VOL.demo.Services
{
    public partial class StockInOrderModelService
    {
        /// <summary>
        /// 分页查询入库单
        /// </summary>
        public async Task<WebResponseContent> GetStockInOrderPageListAsync(
            int pageIndex, 
            int pageSize, 
            string stockInCode = null, 
            int? status = null, 
            long? warehouseId = null, 
            DateTime? stockInDate = null,
            long? inOutTypeId = null)
        {
            try
            {
                var result = await _repository.GetStockInOrderPageListAsync(
                    pageIndex, pageSize, stockInCode, status, warehouseId, stockInDate, inOutTypeId);

                return new WebResponseContent
                {
                    Status = true,
                    Message = "查询成功",
                    Data = new
                    {
                        Data = result.Data,
                        TotalCount = result.TotalCount,
                        PageIndex = pageIndex,
                        PageSize = pageSize,
                        TotalPages = (int)Math.Ceiling((double)result.TotalCount / pageSize)
                    }
                };
            }
            catch (Exception ex)
            {
                return new WebResponseContent
                {
                    Status = false,
                    Message = $"查询失败：{ex.Message}"
                };
            }
        }

        /// <summary>
        /// 根据条件查询入库单列表
        /// </summary>
        public async Task<List<StockInOrderModel>> FindAsync(Expression<Func<StockInOrderModel, bool>> predicate, bool filterDeleted = true)
        {
            return await repository.FindAsync(predicate, filterDeleted);
        }

        /// <summary>
        /// 保存入库单（主表+明细表，使用事务）
        /// </summary>
        public async Task<WebResponseContent> SaveStockInOrderWithItemsAsync(SaveStockInOrderRequest request)
        {
            return repository.DbContextBeginTransaction(() =>
            {
                try
                {
                    // 保存入库单主表
                    var saveModel = new SaveModel
                    {
                        MainData = new Dictionary<string, object>
                        {
                            ["stockInCode"] = request.StockInOrder.stockInCode,
                            ["warehouseId"] = request.StockInOrder.warehouseId,
                            ["stockInDate"] = request.StockInOrder.stockInDate,
                            ["relatedOrderCode"] = request.StockInOrder.relatedOrderCode,
                            ["supplierId"] = request.StockInOrder.supplierId,
                            ["contactPerson"] = request.StockInOrder.contactPerson,
                            ["contactPhone"] = request.StockInOrder.contactPhone,
                            ["userId"] = request.StockInOrder.userId,
                            ["remark"] = request.StockInOrder.remark,
                            ["status"] = request.StockInOrder.status ?? 1,
                            ["inOutTypeId"] = request.StockInOrder.inOutTypeId,
                            ["IsDel"] = 0,
                            ["CreateDate"] = DateTime.Now
                        }
                    };

                    var mainResult = base.Add(saveModel);
                    if (!mainResult.Status)
                    {
                        return mainResult;
                    }

                    // 保存入库明细
                    if (request.OrderItems != null && request.OrderItems.Count > 0)
                    {
                        var goodsIds = request.OrderItems.Select(item => item.GoodsId).Distinct().ToList();

                        // 从货品信息表获取货品详细信息
                        var productService = AutofacContainerModule.GetService<IproductinformationmodelService>();
                        var products = productService.GetProductsByIdsAsync(goodsIds).Result;
                        var productDict = products.ToDictionary(p => p.Id, p => p);

                        // 从进货单明细获取进货相关信息
                        var purchaseOrderItemService = AutofacContainerModule.GetService<IPurchaseOrderItemModelService>();
                        var purchaseItems = purchaseOrderItemService.GetItemsByOrderCodeAsync(request.StockInOrder.relatedOrderCode).Result;
                        var purchaseItemDict = purchaseItems.ToDictionary(p => p.GoodsId, p => p);

                        var stockInItems = request.OrderItems.Select(item =>
                        {
                            var product = productDict.ContainsKey(item.GoodsId) ? productDict[item.GoodsId] : null;
                            var purchaseItem = purchaseItemDict.ContainsKey(item.GoodsId) ? purchaseItemDict[item.GoodsId] : null;

                            return new StockInOrderItemModel
                            {
                                StockInCode = request.StockInOrder.stockInCode,
                                GoodsId = item.GoodsId,
                                GoodsCode = product?.goodsCode ?? "",
                                GoodsName = product?.goodsName ?? "",
                                SpecModel = product?.specModel ?? "",
                                UnitId = item.UnitId ?? product?.UnitId,
                                goodsTypeId = product?.productTypeId,
                                purchaseQuantity = purchaseItem?.PurchaseQty,
                                thisTimeQuantity = item.thisTimeQuantity,  // 本次入库数量（支持分批入库）
                                stockPosition = item.stockPosition,  // 修复：添加库位ID字段
                                purchasePrice = (int?)(purchaseItem?.PurchasePrice ?? 0),
                                upprice = item.upprice,  // 本次入库金额
                                batchNo = item.batchNo,
                                productionDate = item.productionDate,
                                expireDate = item.expireDate,
                                remark = item.ItemRemark,
                                IsDel = (sbyte)0,  // 修复：类型转换为sbyte
                                CreateDate = DateTime.Now
                            };
                        }).ToList();

                        var stockInOrderItemService = AutofacContainerModule.GetService<IStockInOrderItemModelService>();
                        var itemResult = stockInOrderItemService.AddItemsAsync(stockInItems).Result;
                        if (!itemResult)
                        {
                            return new WebResponseContent { Status = false, Message = "保存入库明细失败" };
                        }
                    }

                    return new WebResponseContent { Status = true, Message = "保存成功" };
                }
                catch (Exception ex)
                {
                    return new WebResponseContent { Status = false, Message = $"保存失败：{ex.Message}" };
                }
            });
        }
    }
}

